package com.taobao.pamirs.schedule.taskmanager;

import com.taobao.pamirs.schedule.cron.CronExpression;
import com.taobao.pamirs.schedule.util.ScheduleUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class PauseOrResumeScheduleTask extends TimerTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(HeartBeatTimerTask.class);

    public static int TYPE_PAUSE = 1;
    public static int TYPE_RESUME = 2;

    int type;

    Timer timer;
    String cronTabExpress;
    TBScheduleManager manager;

    public PauseOrResumeScheduleTask(TBScheduleManager aManager, Timer aTimer, int aType, String aCronTabExpress) {
        this.type = aType;
        this.timer = aTimer;
        this.manager = aManager;
        this.cronTabExpress = aCronTabExpress;
    }

    @Override
    public void run() {
        try {
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
            this.cancel();//取消调度任务
            Date current = new Date(System.currentTimeMillis());
            CronExpression cexp = new CronExpression(this.cronTabExpress);
            Date nextTime = cexp.getNextValidTimeAfter(current);
            if (this.type == TYPE_PAUSE) {
                manager.pause("到达终止时间,pause调度");
                this.manager.getScheduleServer().setNextRunEndTime(ScheduleUtil.transferDataToString(nextTime));
            } else {
                manager.resume("到达开始时间,resume调度");
                this.manager.getScheduleServer().setNextRunStartTime(ScheduleUtil.transferDataToString(nextTime));
            }
            this.timer.schedule(new PauseOrResumeScheduleTask(this.manager, this.timer, this.type, this.cronTabExpress), nextTime);
        } catch (Throwable ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
}
